import { getToken } from '@/utils/auth'
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import router from '../router'
import store from '../store'
// import qs from 'qs'

// var loading

// function startLoading () {
//   loading = Loading.service({
//     lock: true,
//     text: '加载中,请稍等'
//   })
// }

// function endLoading () {
//   loading.close()
// }
// 声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
// 调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
// var needLoadingRequestCount = 0
// export function showFullScreenLoading () {
//   if (needLoadingRequestCount === 0) {
//     startLoading()
//   }
//   needLoadingRequestCount++
// }

// export function tryHideScreenLoading () {
//   if (needLoadingRequestCount <= 0) {
//     return
//   }
//   needLoadingRequestCount--
//   if (needLoadingRequestCount === 0) {
//     endLoading()
//   }
// }
// 创建axios实例
const service = axios.create({
  // baseURL: 'http://test.qingningmeng.top:80/api',
  baseURL: process.env.BASE_API, // api的base_url
  // baseURL: 'https://nei.netease.com/api/apimock/1cded3afb72592eeb59583c08261df0c/api/',
  // process.env.BASE_API, // api的base_url
  // 'http://test.qingningmeng.top:80/api',
  timeout: 15000, // 请求超时时间
  // transformRequest: [function (data) {
  //     data = qs.stringify(data);
  //     return data;
  // }],
  headers: {
    // 'Content-Type':'application/x-www-form-urlencoded',
    // 'X-Requested-With':'XMLHttpRequest'
  },
  withCredentials: true
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['authorization'] = `TOKEN ${getToken()}` // Let every request carry token.
  }
  // if(config.method === 'post') {
  //   config.data = qs.stringify(config.data);
  // }
  // showFullScreenLoading()
  return config
}, error => {
  // tryHideScreenLoading()
  // Do something with request error

  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * 按照正常HTTP状态码 返回
  */
    const res = response.data
    const status = response.status
    if (status !== 200 && status !== 201 && status !== 204 && status !== 302) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      // tryHideScreenLoading()
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('error')
    } else {
      if (response.data.msg === 'Session为空，请重新登录') {
        Message({
          message: '请您先登录',
          type: 'error',
          duration: 1000
        })
        console.log(router)
        router.push({
          path: '/login',
          query: {
            redirect: router.fullPath
          }
        })
      }
      // Message({
      //   message: response.data.msg,
      //   type: 'error',
      //   duration: 2000
      // })
      // tryHideScreenLoading()
      return response.data
      // return Promise.reject('error')
    }
  },
  error => {
    const response = error.response
    if (response.status === 403) {
      if (response.data.detail === 'Authentication credentials were not provided.') {
        Message({
          message: '您登陆已经过期, 请重新登录',
          type: 'warning'
        })

        router.push({
          path: '/login',
          query: {
            redirect: router.fullPath
          }
        })
        // tryHideScreenLoading()
        return Promise.reject(error)
      } else {
        this.endLoading()
        // tryHideScreenLoading()
        router.push({ path: '/403' })
      }
    } else if (response.status === 401) {
      MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
    }
    Message({
      message: response.data.detail,
      type: 'error',
      duration: 5 * 1000
    })
    // tryHideScreenLoading()
    this.endLoading()
    return Promise.reject(error)
  }
)

export default service
